import { constantRoutes } from '@/router'
import { getUserPermission } from '@/api/user'
import routeMap from '@/router/components'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

// const formatRoutes = function (routes, routeData) {
//   if (!routeData) {
//     routeData = {
//       name: 'home',
//       path: '/home',
//       // 组件匹配成功的话才可以访问具体的页面
//       component: routeMap['home'],
//       children: [],
//     };
//   }
//   routes.length && routes.forEach(route => {
//     if (route.component) {
//       debugger
//       route.component = routeMap[route.component];
//       routeData.children.push({
//         path: route.path,
//         name: route.index,
//         component: route.component,
//         meta: {
//           title: route.title,
//         },
//       })
//     }
//     if (route.children && route.children.length) {
//       formatRoutes(route.children, routeData);
//     }
//   });

//   return routeData;
// };


/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routers) {
  // 遍历后台传来的路由字符串，转换为组件对象
  let accessedRouters = routers.filter(router => {
    if (router.meta) {
      // 默认图标处理
      router.meta.icon = router.meta.icon ? router.meta.icon : "example";
    }
    // if (router.component === "main") {
    //   // Main组件特殊处理
    //   router.component = AppMain;
    // }
    if (router.component) {
      //处理组件---重点
      router.component = routeMap[router.component];
    }
    //存在子集
    if (router.children && router.children.length) {
      router.children = filterAsyncRoutes(router.children);
    }
    return true;
  });
  return accessedRouters;
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  getUserPermission({ commit }) {
    return new Promise((resolve, reject) => {
      getUserPermission().then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
      // commit('SET_TOKEN', username)
      // setToken(username)
    })
  },
  generateRoutes({ commit }, routes) {
    return new Promise(resolve => {
      let accessedRoutes = filterAsyncRoutes(routes.children)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
